package cn.team11.smarteye.impl;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.media.AudioDeviceInfo;
import android.media.AudioManager;
import android.os.Build;
import android.view.Surface;
import android.view.SurfaceView;

import com.eques.icvss.core.module.user.BuddyType;

import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.TimeUnit;

import cn.team11.sds.dayi.R;
import cn.team11.smarteye.contract.VideoCallContract;
import cn.team11.smarteye.service.CatEyeService;
import cn.team11.smarteye.utils.TimeUtils;
import cn.team11.smarteye.utils.ToastUtil;
import io.reactivex.Observable;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;

/**
 * Created by Murphy on 2017/10/19.
 */

public class VideoCallPresenterImpl implements VideoCallContract.Presenter {

    private VideoCallContract.View mView;
    private AudioManager mAudioManager;
    private int currentVolume;
    private boolean isWiredHeadSet;



    public VideoCallPresenterImpl(VideoCallContract.View mView) {
        this.mView = mView;
        mView.setPresenter(this);
        init();
    }


    private void init(){
        mAudioManager = (AudioManager) mView.getContext().getSystemService(Context.AUDIO_SERVICE);
        currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        if (currentVolume == 0) currentVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        isWiredHeadSet = isHeadsetOn();
        if (!isWiredHeadSet) openSpeaker();
        registerHeadsetPlugReceiver();
    }

    @Override
    public void start() {

    }

    @Override
    public void destroy() {
        closeSpeaker();
        if (headsetPlugReceiver != null){
            mView.getContext().unregisterReceiver(headsetPlugReceiver);
        }
    }

    @Override
    public String openVideoCall(String uid, Surface surface, boolean isPureAudio) {
        if (CatEyeService.icvss != null){
            String callid = CatEyeService.icvss.equesOpenCall(uid, surface, isPureAudio);
            return callid;
        }
        return null;
    }

    @Override
    public String openAudioCall(String uid, SurfaceView view, Drawable d, boolean isPureAudio) {
        if (CatEyeService.icvss != null){
            String callid = CatEyeService.icvss.equesOpenCall(uid, view, d, isPureAudio);
            return callid;
        }
        return null;
    }

    @Override
    public void hangupVideoCall(String sid) {
        if (CatEyeService.icvss != null) {
            CatEyeService.icvss.equesCloseCall(sid);

        }
    }

    @Override
    public Observable<String> countVideoTime() {
        return Observable.interval(0,1, TimeUnit.SECONDS)
                .map(new Function<Long, String>() {
                    @Override
                    public String apply(@NonNull Long aLong) throws Exception {
                        return TimeUtils.long2Time(aLong*1000);
                    }
                });
    }


    private void openSpeaker(){//打开扬声器
        try {
            if (mAudioManager != null){
                currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                if (!mAudioManager.isSpeakerphoneOn()) {
                    mAudioManager.setSpeakerphoneOn(true);
                    mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void closeSpeaker(){//关闭扬声器
        try {
            if (mAudioManager.isSpeakerphoneOn()) {
                currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                mAudioManager.setSpeakerphoneOn(false);
                mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);
            }
        } catch (Exception e){
            e.printStackTrace();
        }

    }

    /**设置音频模式*/
    public void setAudioMute(String callId, boolean isMute){

        if(isMute){//开启静音
            //记录当前音量
            currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            //静音
            if (mAudioManager != null){
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                    mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_MUTE, 0);
                } else {
                    mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
                }
            }

            if(callId != null && CatEyeService.icvss != null){//同时关掉麦克风和播放声音
                CatEyeService.icvss.equesAudioPlayEnable(false, callId);
                CatEyeService.icvss.equesAudioRecordEnable(false, callId);
            }
            mView.updateMuteBtState(true);
            mView.showToast(ToastUtil.NORMAL_TOAST, mView.getContext().getString(R.string.silence_mode));
        }else{//取消静音
            if (currentVolume == 0) currentVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);
            enableSpeaker(callId, false);
            mView.updateMuteBtState(false);
            mView.showToast(ToastUtil.NORMAL_TOAST, mView.getContext().getString(R.string.speak_mode));
        }
    }


    @Override
    public void enableSpeaker(String callid, boolean enable) {
        if (CatEyeService.icvss != null && callid != null && !StringUtils.isEmpty(callid)){
            if (enable){//开始说话
                //通话声音
                CatEyeService.icvss.equesAudioPlayEnable(false, callid);
                //打开麦克风录音
                CatEyeService.icvss.equesAudioRecordEnable(true, callid);
                //关闭扬声器
                closeSpeaker();
            } else {//停止说话
                //播放声音
                CatEyeService.icvss.equesAudioPlayEnable(true, callid);
                //关闭麦克风
                CatEyeService.icvss.equesAudioRecordEnable(false, callid);
                //打开扬声器
                openSpeaker();
            }
        }
    }

    @Override
    public void screenShot(String path) {
        if (CatEyeService.icvss != null){
            CatEyeService.icvss.equesSnapCapture(BuddyType.TYPE_WIFI_DOOR_R22, path);
        }
    }


    /**检查耳机状态*/
    private boolean isHeadsetOn() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return mAudioManager.isWiredHeadsetOn() || mAudioManager.isBluetoothA2dpOn();
        } else {
            AudioDeviceInfo[] devices = mAudioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS);
            for (int i = 0; i < devices.length; i++) {
                AudioDeviceInfo device = devices[i];
                if (device.getType() == AudioDeviceInfo.TYPE_WIRED_HEADPHONES
                        || device.getType() == AudioDeviceInfo.TYPE_BLUETOOTH_A2DP
                        || device.getType() == AudioDeviceInfo.TYPE_BLUETOOTH_SCO) {
                    return true;
                }
            }
        }
        return false;
    }

    private void registerHeadsetPlugReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.action.HEADSET_PLUG");
        mView.getContext().registerReceiver(headsetPlugReceiver, intentFilter);

    }


    private BroadcastReceiver headsetPlugReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("android.intent.action.HEADSET_PLUG".equals(action)) {
                if (intent.hasExtra("state")) {
                    if (intent.getIntExtra("state", 0) == 0) {
                        //耳机断开
                        openSpeaker();
                    } else if(intent.getIntExtra("state", 0) == 1){
                        //耳机插入
                        closeSpeaker();
                    }
                }
            }
        }

    };
}
